<template>
  <view class="container">
    <view class="form-card">
      <up-form :model="fuelRecord" :borderBottom="true" labelWidth="160rpx" ref="fuelRecordFormRef"
        :rules="fuelRecordRules">
        <!-- 日期 -->
        <up-form-item label="日期" prop="date" required>
          <view class="date-picker-trigger" @tap="datePickerShow = true">
            <text class="date-text">{{ fuelRecord.date || '请选择日期' }}</text>
            <up-icon name="calendar" size="34rpx" color="#888" class="date-icon"></up-icon>
          </view>
          <up-datetime-picker mode="date" :show="datePickerShow" v-model="datePickerValue"
            @confirm="datePickerShow = false" @cancel="datePickerShow = false" @close="datePickerShow = false" />
        </up-form-item>

        <!-- 里程 -->
        <up-form-item label="里程" prop="mileage" required>
          <up-input v-model="fuelRecord.mileage" clearable type="digit" placeholder="请输入里程数" border="bottom" />
        </up-form-item>

        <!-- 油量 -->
        <up-form-item label="油量" prop="liters" required>
          <up-input v-model="fuelRecord.liters" clearable type="digit" placeholder="请输入加油量" border="bottom" />
        </up-form-item>

        <!-- 油价 -->
        <up-form-item label="油价" prop="price_per_liter" required>
          <up-input v-model="fuelRecord.price_per_liter" clearable type="digit" placeholder="请输入油价" border="bottom" />
        </up-form-item>

        <!-- 油枪金额 -->
        <up-form-item label="油枪金额" prop="oil_pump_amount" required>
          <up-input v-model="fuelRecord.oil_pump_amount" clearable type="digit" placeholder="请输入油枪金额" border="bottom" />
        </up-form-item>

        <!-- 实付金额 -->
        <up-form-item label="实付金额" prop="actual_amount" required>
          <up-input v-model="fuelRecord.actual_amount" clearable type="digit" placeholder="请输入实付金额" border="bottom">
            <template #suffix>
              <up-icon v-if="fuelRecord.oil_pump_amount" name="file-text" color="#1989fa" size="36rpx"
                @tap="copyOilPumpAmount" />
            </template>
          </up-input>
        </up-form-item>

        <!-- 是否加满 -->
        <up-form-item label="是否加满" prop="is_full">
          <up-switch v-model="fuelRecord.is_full" :active-value="1" :inactive-value="0"></up-switch>
        </up-form-item>
      </up-form>

      <!-- 加油记录图片 -->
      <up-form-item label="图片" prop="image">
        <up-upload :fileList="fileList" multiple :maxCount="2" accept="image" @afterRead="handleAfterRead" autoDelete>
        </up-upload>
      </up-form-item>

      <view class="form-footer">
        <up-button @tap="handleAnalyzeFuelRecord" type="error" :disabled="loading">识别</up-button>
        <up-button @tap="handleCancel" class="cancel-button" :disabled="loading">取消</up-button>
        <up-button type="primary" @tap="saveRecord" class="confirm-button" :disabled="loading">确认</up-button>
      </view>
    </view>

    <!-- 页面遮罩层 -->
    <up-overlay :show="loading" :mask-click-able="false">
      <view class="loading-wrapper">
        <view class="loading-content" @tap.stop>
          <view class="loading-spinner"></view>
          <text class="loading-text">加油记录图片识别中...</text>
        </view>
      </view>
    </up-overlay>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance, watch } from 'vue'
import * as fillupApi from '../../api/fuel'
import { getCurrentOilPriceWithNextUpdate } from '../../utils/oilPrice'
import { recognizeFuelRecord } from '../../utils/qwen-vl-ocr'

// 状态管理
const fuelRecord = ref({
  id: null,
  car_id: null,
  date: '',
  mileage: '',
  liters: '',
  price_per_liter: '',
  oil_pump_amount: '',
  actual_amount: '',
  is_full: 1
})
const currentCarId = ref(null)        // 关联的车ID
const datePickerShow = ref(false)     // 日期选择器是否显示
const fuelRecordFormRef = ref(null)   // 表单实例引用
const loading = ref(false)            // 页面加载状态

// 当前油价信息
const oilPriceInfo = ref({
  oilPrices: 0.00,
  nextUpdate: 'YYYY-MM-DD'
})
// 上传的图片列表
const fileList = ref([])

// 表单验证规则
const fuelRecordRules = ref({
  mileage: [{ required: true, message: '请输入里程数', type: 'number', trigger: ['blur', 'change'] }],
  liters: [{ required: true, message: '请输入加油量', type: 'number', trigger: ['blur', 'change'] }],
  price_per_liter: [{ required: true, message: '请输入单价', type: 'number', trigger: ['blur', 'change'] }],
  oil_pump_amount: [{ required: true, message: '请输入油枪金额', type: 'number', trigger: ['blur', 'change'] }],
  actual_amount: [{ required: true, message: '请输入实付金额', type: 'number', trigger: ['blur', 'change'] }],
})

// 日期选择器绑定值（时间戳）
const datePickerValue = computed({
  get: () => {
    return fuelRecord.value.date
      ? new Date(fuelRecord.value.date).getTime()
      : Date.now()
  },
  set: (timestamp) => {
    const d = new Date(timestamp)
    fuelRecord.value.date = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
  }
})

// 监听油量和油价变化，计算油枪金额
watch(
  () => [fuelRecord.value.liters, fuelRecord.value.price_per_liter],
  ([liters, price]) => {
    const l = Number(liters)
    const p = Number(price)

    if (l > 0 && p > 0) {
      fuelRecord.value.oil_pump_amount = (l * p).toFixed(2)
    }
  }
)

// 点击复制油枪金额到实付金额
const copyOilPumpAmount = () => {
  if (fuelRecord.value.oil_pump_amount) {
    fuelRecord.value.actual_amount = fuelRecord.value.oil_pump_amount
  }
}

// 加载油价数据
const loadOilPrice = async () => {
  try {
    // 获取当前油价和下一次更新时间
    const oilPriceResult = await getCurrentOilPriceWithNextUpdate()
    oilPriceInfo.value = oilPriceResult
  } catch (error) {
    uni.$u.toast('加载油价数据失败')
    console.error('加载油价数据失败:', error)
  }
}

// 上传图片后处理
const handleAfterRead = (event) => {
  const files = Array.isArray(event.file) ? event.file : [event.file]
  files.forEach(file => {
    fileList.value.push({
      url: file.url,
      status: 'success',
      message: ''
    })
  })
}

// 点击按钮调用 Qwen-VL-OCR 接口识别加油记录
async function handleAnalyzeFuelRecord() {
  if (fileList.value.length === 0) {
    uni.showToast({ title: "请上传至少一张图片", icon: "none" });
    return;
  }

  // 显示加载状态
  loading.value = true;

  const imagePaths = fileList.value.map(f => f.url || f.path);
  try {
    const result = await recognizeFuelRecord(imagePaths);
    fuelRecord.value = result;
    fuelRecord.value.car_id = currentCarId.value;
    fuelRecord.value.is_full = 1;
  } catch (err) {
    console.error(err);
    uni.showToast({ title: "识别失败", icon: "none" });
    fileList.value = []
  } finally {
    fileList.value = []
    loading.value = false;
  }
}

// 初始化页面数据
const initData = async (recordId) => {
  if (recordId) {
    // 编辑模式：加载现有记录
    try {
      const record = await fillupApi.getFuelRecordById(recordId)
      fuelRecord.value = record
    } catch (error) {
      console.error('加载记录失败:', error)
      uni.$u.toast('加载记录失败')
    }
  } else {
    // 新增模式：设置默认数据
    const today = new Date()
    const defaultDate = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`

    fuelRecord.value = {
      id: null,
      car_id: currentCarId.value,
      date: defaultDate,
      mileage: '',
      liters: '',
      price_per_liter: oilPriceInfo.value.oilPrices || 0.00,
      oil_pump_amount: '',
      actual_amount: '',
      is_full: 1
    }
  }
}

// 保存记录
const saveRecord = () => {
  // 校验表单
  fuelRecordFormRef.value.validate().then(async valid => {
    if (valid) {
      try {
        const data = {
          ...fuelRecord.value,
          mileage: Number(fuelRecord.value.mileage) || 0,
          liters: Number(fuelRecord.value.liters) || 0.00,
          price_per_liter: Number(fuelRecord.value.price_per_liter) || 0.00,
          oil_pump_amount: Number(fuelRecord.value.oil_pump_amount) || 0.00,
          actual_amount: Number(fuelRecord.value.actual_amount) || 0.00,
        }
        let res = false

        if (fuelRecord.value.id) {
          // 更新记录
          res = await fillupApi.updateFuelRecord(fuelRecord.value.id, data)
        } else {
          // 添加记录
          res = await fillupApi.addFuelRecord(data)
        }

        if (res) {
          uni.$u.toast(fuelRecord.value.id ? '更新成功' : '添加成功')
          // 延迟返回，确保用户看到提示
          setTimeout(() => {
            uni.navigateBack()
          }, 1000)
        } else {
          uni.$u.toast(fuelRecord.value.id ? '更新失败' : '添加失败')
        }
      } catch (error) {
        console.error('保存记录失败:', error)
        uni.$u.toast('保存失败，请重试')
      }
    } else {
    }
  }).catch(() => {
  });
}

// 取消操作
const handleCancel = () => {
  uni.navigateBack()
}

// 初始化
onMounted(async () => {
  // 通过getCurrentInstance获取参数
  const instance = getCurrentInstance()
  const attrs = instance?.attrs || {}
  const { carId, recordId } = attrs || {}

  // 确保car_id已设置
  if (!carId) {
    uni.$u.toast('请从列表选择或添加新的车源')
    uni.navigateBack()
    return
  }
  currentCarId.value = carId

  // 设置导航栏标题
  const title = recordId ? '编辑加油记录' : '新增加油记录'
  uni.setNavigationBarTitle({
    title: title
  })
  // 加载油价数据
  await loadOilPrice()
  await initData(recordId)
})
</script>

<style lang="scss" scoped>
/** 容器样式 */
.container {
  min-height: 100vh;
  background-color: #f8f9fa;
  padding: 20rpx;
}

/** 卡片样式 */
.form-card {
  background-color: #ffffff;
  padding: 20rpx 40rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

/** 日期选择器触发样式 */
.date-picker-trigger {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 0;
  color: #666;
  padding-bottom: 10rpx;
  border-bottom: 1rpx solid #e9ecef;
}

.date-text {
  padding-left: 20rpx;
  color: #333;
  font-size: 28rpx;
}

.date-icon {
  margin-left: auto
}

/** 表单页脚样式 */
.form-footer {
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  gap: 20rpx;
}

/** 页脚按钮样式 */
.form-footer up-button {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  font-size: 32rpx;
  border-radius: 16rpx;
  box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.08);
}

/** 取消按钮样式 */
.cancel-button {
  background-color: #f5f5f5;
  color: #666;
  border: none;
  margin-right: 20rpx;
}

/** 确认按钮样式 */
.confirm-button {
  background-color: #1989fa;
  color: #fff;
  border: none;
}

/** 遮罩层样式 */
.loading-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 100%;
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 48rpx 64rpx;
  background: rgba(28, 28, 28, 0.88);
  backdrop-filter: blur(16rpx);
  -webkit-backdrop-filter: blur(16rpx);
  border-radius: 24rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.2);
  min-width: 340rpx;
  text-align: center;
}

.loading-spinner {
  width: 64rpx;
  height: 64rpx;
  border: 6rpx solid rgba(255, 255, 255, 0.3);
  border-top-color: #ffffff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.loading-text {
  color: #ffffff;
  font-size: 30rpx;
  font-weight: 500;
  margin-top: 24rpx;
  line-height: 1.4;
  letter-spacing: 0.5rpx;
}

/* 旋转动画 */
@keyframes spin {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}
</style>